package com.markix.security;

import com.markix.dao.UserToAuthDao;
import com.markix.entity.UserToAuthPO;
import com.markix.security.oauth2login.WebAttributes;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.time.LocalDateTime;

/**
 * @author markix
 * @date 2022/9/2 17:12
 */
public class FormLoginAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {

    private UserToAuthDao userToAuthDao;

    public FormLoginAuthenticationSuccessHandler(UserToAuthDao userToAuthDao) {
        this.userToAuthDao = userToAuthDao;
    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException {
        HttpSession session = request.getSession(false);
        if(session != null){
            String bind = request.getParameter(WebAttributes.LOGIN_BIND);
            if(Boolean.valueOf(bind)){
                String type = (String) session.getAttribute(WebAttributes.THIRD_TYPE);
                Authentication auth = (Authentication) session.getAttribute(WebAttributes.THIRD_AUTHENTICATION);
                if(type != null && auth != null){
                    String username = SecurityContextHolder.getContext().getAuthentication().getName();
                    //绑定第三方帐号
                    String identity = auth.getName();
                    userToAuthDao.save(new UserToAuthPO().setType(type).setIdentity(identity).setUserId(username).setTime(LocalDateTime.now().toString()));
                }
            }
            // clean
            session.removeAttribute(WebAttributes.THIRD_TYPE);
            session.removeAttribute(WebAttributes.THIRD_AUTHENTICATION);
        }
        super.onAuthenticationSuccess(request, response, authentication);
    }


}
